const crypto = require('crypto');
const axios = require('axios');
const moment = require('moment');
const utils = require('../lib/utils');

/**
 * {"msg":"success","code":"0","data":{"token":"c070800f-f50f-42f7-ac51-2327501c702f","expireTime":1719052952845}}
 */
function getSign(id, pwd, ts){
    return utils.MD5(`${id}${pwd}${ts}`, true);
}

async function send(params){
    let serverUrl = 'http://124.221.69.238:8020/inter/sms/V2/mt';
    let ts = new moment().format('YYYYMMDDHHmmss');
    let sign = getSign(params.account, params.pwd, ts);
    let config = {
        headers : {
            appKey : params.account,
            timestamp : ts,
            sign,
            "content-type" : "application/json;charset=UTF-8"
        }
    }
    let reqData = {
        mobiles : [params.mobile],
        content : params.content,
        customId : params._id,
        extendedCode : params.ext
    }
    let result = {}
    try{
        log.info('mt request to server:', reqData)
        let res = await axios.post(serverUrl, reqData, config);
        res = res.data;
        if(res.success){
            result.status = 1;
            result.mt_msg_id = res.result.mobileList[0].smsId;
            result.report_status = 0;
        }else{
            result.status = 2;
            result.mt_msg_id = '';
            result.report_status = 2;
            result.report_desc = 'submit_fail';
            result.report_time = new Date();
        }
        log.info('mt response from server:', res.data)
    }catch(err){
        log.error('mt server error:', err.message)
        console.log(err)
        result.status = 2;
        result.report_status = 2;
        result.report_desc = 'CHN_ERR'
        result.report_time = new Date();
    }finally {
        result.send_time = new Date();
        try{
            let r = await models.mtMsg.findByIdAndUpdate(params._id, {$set: result});
            //r = update success number
        }catch(e1){
            log.error('update submit resp err', e1.message)
        }
    }
}

module.exports = { send }
